package com.fenqile.pop.utility;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

/**
 * 字段选择列表，用于查询时指定返回的字段。
 * 
 * @author Coby [cobylin@live.com] 2017
 */
public class FieldOpt<T> {
	
	protected Class<T> targetClass;
	
	protected Set<String> allowedFields = new HashSet<>();
	protected Set<String> fields = new HashSet<>();
	
	public FieldOpt(Class<T> targetClass) {
		this.targetClass = targetClass;
		for (Field field : targetClass.getFields())
			allowedFields.add(field.getName());
		fields = new HashSet<>();
	}
	
	public void addAll() {
		fields.addAll(allowedFields);
	}
	
	public void add(String...names) {
		
		for (String name : names) {
			if (allowedFields.contains(name))
				fields.add(name);
			else
				throw new IllegalArgumentException("not allow field: " + name);
		}
		
	}
	
	public void remove(String name) {
		fields.remove(name);
	}
	
	public void clear() {
		fields.clear();
	}
	
	@Override
	public String toString() {
		if (fields.isEmpty()) return "";
		StringBuilder sb = new StringBuilder();
		fields.forEach(f -> sb.append(f).append(','));
		sb.setLength(sb.length()-1);
		return sb.toString();
	}
	
}
